package com.eascs.admin.o2o.applyAssessment.service;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.applyAssessment.dao.ApplyAssessmentDao;
import com.eascs.admin.o2o.applyAssessment.entity.ApplyAssessmentEntity;
import com.eascs.admin.o2o.applyAssessment.entity.ApplyAssessmentVo;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class ApplyAssessmentService {

	@Autowired
	ApplyAssessmentDao applyDao;
	@Reference
	WorkFlowService workFlowService;
	@Reference
	EmployeeService employeeDubboService;

	/**
	 * 提前进入考核期申请 --> 搜索查询页面
	 * 
	 * @param vo
	 * @return
	 */
	public PageResult<Object[]> getApplyAssessmentByPage(ApplyAssessmentVo vo) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, vo.getPageSize(), vo.getPageIndex());
		StringBuffer querySql = new StringBuffer();
		// ======== 仅展示用 ==============
		querySql.append(
				" SELECT OAA.id,OAA.bill_code,OAA.name AS name,OAA.province_name AS provinceName,OAA.position AS position,OAA.hiredate AS hiredate,OAA.team,OAA.wf_status FROM o2o_apply_assessment OAA  ");
		querySql.append(" WHERE  1=1 AND /**DATA_PERMISSION(oll.ltd)**/ ");
		querySql.append("  OAA.status=1 ");//1为正常 , 2为删除
		if (!StringUtil.isEmpty(vo.getName())) {// 
			querySql.append(" AND name LIKE ? ");
			sqlPageQuery.addLikeParam(vo.getName());
		}
		if (!StringUtil.isEmpty(vo.getPosition())) {// 
			querySql.append(" AND position = ? ");// 
			sqlPageQuery.addParam(vo.getPosition());
		}
		if (!StringUtil.isEmpty(vo.getHiredateStart())) {//
			querySql.append(" AND hiredate >= ? ");
			sqlPageQuery.addParam(vo.getHiredateStart());
		}
		if (!StringUtil.isEmpty(vo.getHiredateEnd())) {// 
			querySql.append(" AND hiredate < ?");
			sqlPageQuery.addParam(
					DateUtils.formateStandDate(DateUtils.addDate(DateUtils.formateStandDate(vo.getHiredateEnd()), 1)));
		}
		if (!StringUtil.isEmpty(vo.getProvinceCode())) {// 待改,省区数据字典对不上 ,山西为22,此处显示46
			querySql.append(" AND province_code = ? ");
			sqlPageQuery.addParam(vo.getProvinceCode());
		}
		querySql.append(" ORDER BY hiredate ");
		// -----------------
		sqlPageQuery.setQuerySql(querySql.toString());
		return applyDao.findDataWithPage(sqlPageQuery);
	}

	/**
	 * 提前进入考核期申请 -->流程单号 单据详情
	 * 
	 * @param 流程单号id
	 * @return
	 */
	public ApplyAssessmentEntity getEntityById(String id) {
		
		return applyDao.getById(ApplyAssessmentEntity.class, id);
	}

	/**
	 * 提前进入考核期申请 -->新增页面数据插入保存
	 * 
	 * @param entity
	 * @return
	 * @return
	 */
	public int newApplySave(ApplyAssessmentEntity entity) {
		
		return applyDao.insert(entity);
	}

	public ModelResult<Boolean> startUp(ApplyAssessmentEntity entity) {
		try {
		//这句代码能不能查出完整的entity有待验证
		ApplyAssessmentEntity applyEntity = applyDao.getById(ApplyAssessmentEntity.class, entity.getId() );
		WFRequestParam param = new WFRequestParam();
		param.setReferId(applyEntity.getId());//主键id
//		param.setReferId(id);//主键id
		param.setReferCode(applyEntity.getBillCode());//流程单号???
		param.setReferUrl("/rApplyAssessment/view_flow");//详情页面
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("TQKH");//对应流程
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(applyEntity.getOrgId());
		//校验
		//
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			applyDao.processApplyStart(applyEntity.getId());
		} else {
//			logger.error("启动一批经销商合作方申请失败，一批经销商合作方id：【{}】，错误信息{}", jxsPartnerId, modelResult.getErrMsg());
		}
		return modelResult;
	} catch (Exception e) {
//		logger.error("启动一批经销商合作方申请失败，一批经销商合作方id：【{}】，错误：{}，", jxsPartnerId, e.getMessage());
		return new ModelResult<Boolean>("applyEntity error", "启动提前申请进入考核期申请失败");
	}
		
	}
/**
 * 删除deleteApplyService
 * @param id
 * @return
 */
	public ModelResult<Boolean> deleteApplyService(String id) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (StringUtils.isBlank(id)) {
			modelResult.withError("delete.error", "id is null");
		}
		ApplyAssessmentEntity entity = getEntityById(id);
		entity.setUpdateDate(new Date());
		entity.setUpdatorId(UserHolder.getUser().getNo());
		entity.setUpdatorName((UserHolder.getUser().getCname()));
		entity.setStatus(2);//1正常 , 2删除
		boolean model =applyDao.update(entity);
		modelResult.withModel(model);
		return modelResult;
	}
	

	public ModelResult<Boolean> updateApply(ApplyAssessmentEntity entity) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (entity == null ) {
			modelResult.withError("update.error", "ApplyAssessmentService update is null");
		}
		String id =entity.getId();
		if (StringUtils.isBlank(id)) {
			modelResult.withError("update.error", "ApplyAssessmentService update id is null");
		}
		boolean model =applyDao.update(entity);
		modelResult.withModel(model);
		return modelResult;
	}

	

}
